package com.waypolice.manager.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;

import com.waypolice.base.BaseController;
import com.waypolice.common.pojo.UpmsResult;
import com.waypolice.common.pojo.UpmsResultConstant;
import com.waypolice.common.utils.StringUtil;
import com.waypolice.common.validator.LengthValidator;
import com.waypolice.manager.service.UpmsDictionaryService;
import com.waypolice.pojo.UpmsDictionary;
import com.waypolice.pojo.UpmsDictionaryExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典controller
 * Created by lzh on 2019/3/12.
 */
@Controller
@Api(value = "数据字典", description = "数据字典")
@RequestMapping("/manage/dictionary")
public class UpmsDictionaryController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsDictionaryController.class);

    @Autowired
    public UpmsDictionaryService upmsDictionaryService;

    @ApiOperation(value = "字典首页")
    @RequiresPermissions("upms:dictionary:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/dictionary/index";
    }

    @ApiOperation(value = "字典列表")
    @RequiresPermissions("upms:dictionary:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        UpmsDictionaryExample upmsDictionaryExample = new UpmsDictionaryExample();
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            sort= StringUtil.frontStrongToOracleString(sort);
            upmsDictionaryExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            upmsDictionaryExample.or()
                    .andCodeLike("%" + search + "%");
        }
        List<UpmsDictionary> rows = upmsDictionaryService.selectByExampleForOffsetPage(upmsDictionaryExample, offset, limit);
        long total = upmsDictionaryService.countByExample(upmsDictionaryExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "查询字典")
    @RequiresPermissions("upms:dictionary:read")
    @ResponseBody
    @RequestMapping(value = "/select/{fatherCode}", method = RequestMethod.GET)
    public Object select(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @PathVariable("fatherCode") String fatherCode,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        UpmsDictionaryExample upmsDictionaryExample = new UpmsDictionaryExample();
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            sort= StringUtil.frontStrongToOracleString(sort);
            upmsDictionaryExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(fatherCode)) {
            upmsDictionaryExample.or().andFatherCodeEqualTo(fatherCode);
        }
        List<UpmsDictionary> rows =upmsDictionaryService.selectByExampleForOffsetPage(upmsDictionaryExample, offset, limit);
        long total = upmsDictionaryService.countByExample(upmsDictionaryExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "查询字典不分页")
    @RequiresPermissions("upms:dictionary:read")
    @ResponseBody
    @RequestMapping(value = "/selectNoPagination/{fatherCode}", method = RequestMethod.GET)
    public Object select(
            @PathVariable("fatherCode") String fatherCode) {
        UpmsDictionaryExample upmsDictionaryExample = new UpmsDictionaryExample();
        if (StringUtils.isNotBlank(fatherCode)) {
            upmsDictionaryExample.or().andFatherCodeEqualTo(fatherCode);
        }
        List<UpmsDictionary> rows =upmsDictionaryService.selectByExample(upmsDictionaryExample);
        long total = upmsDictionaryService.countByExample(upmsDictionaryExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增字典")
    @RequiresPermissions("upms:dictionary:create")
    @RequestMapping(value = "/create/{inStr}", method = RequestMethod.GET)
    public String create(@PathVariable("inStr") String inStr, HttpServletRequest request) {
        request.setAttribute("fatherCodeStr",inStr.split("\\&")[0]);
        request.setAttribute("fatherDescStr",inStr.split("\\&")[1]);
        return "/manage/dictionary/create";
    }

    @ApiOperation(value = "新增字典")
    @RequiresPermissions("upms:dictionary:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Object create(UpmsDictionary upmsDictionary) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsDictionary.getDescription(), new LengthValidator(1, 20, "描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        Date time=new Date();
        upmsDictionary.setCtime(time);
        int count = upmsDictionaryService.insertSelective(upmsDictionary);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除字典")
    @RequiresPermissions("upms:dictionary:delete")
    @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        int count = upmsDictionaryService.deleteByPrimaryKeys(ids);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改字典")
    @RequiresPermissions("upms:dictionary:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsDictionary dictionary = upmsDictionaryService.selectByPrimaryKey(id);
        modelMap.put("dictionary", dictionary);
        return "/manage/dictionary/update";
    }

    @ApiOperation(value = "修改字典")
    @RequiresPermissions("upms:dictionary:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") int id, UpmsDictionary upmsDictionary) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsDictionary.getDescription(), new LengthValidator(1, 20, "描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        upmsDictionary.setPkId(id);
        int count = upmsDictionaryService.updateByPrimaryKeySelective(upmsDictionary);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    /**
     * @author:zyp
     * @description 根据字典获取流程名称
     * @date: 2019/3/19 17:29
     * @return
     */
    @ApiOperation(value = "根据字典获取流程名称")
    @RequestMapping(value="/getActivitiName")
//    @RequiresPermissions("upms:dictionary:read")
    @ResponseBody
    public List<UpmsDictionary> getActivitiName(){
        String parentCode = "activitiCode";
        List<UpmsDictionary> dictionarys = upmsDictionaryService.getUpmsDictionaryByCode(parentCode);
        return dictionarys;
    }

}